package top.sehnsucht.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/11/5
 */
@Slf4j
public class Qiniu {
    private static String ACCESS_KEY = "2lL2OmZgmN0C4S3oQGMjJks6vT2wMAqZWYCgkFNM";
    private static String SECRET_KEY  = "03J-EBX5HDdqU8MGUKEGdonYaBgi5jmI3sInePwe";
    private static String BUCKET_NAME = "test-hex";
    private static String KEY = "";
    private static String FILE_PATH = "";


    /**
     * 自定义返回的json格式
     */
    public static void setJson() {
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        StringMap putPolicy = new StringMap();
        putPolicy.put("callbackUrl", "http://api.example.com/qiniu/upload/callback");
        putPolicy.put("callbackBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
        putPolicy.put("callbackBodyType", "application/json");
        long expireSeconds = 3600;
        String upToken = auth.uploadToken(BUCKET_NAME, null, expireSeconds, putPolicy);
        log.info("upToken: " + upToken);
    }

    /**
     * 上传文件
     */
    public static void uploadPic(String key, String filePath) {
        KEY = key;FILE_PATH = filePath;
        //构造一个带指定 Region 对象的配置类,这里可能需要根据自己情况改一下,点进源码看看情况,根据报错改region
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET_NAME);
        try {
            Response response = uploadManager.put(FILE_PATH, KEY, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                ex2.printStackTrace();
            }
        }
    }

    /**
     * 返回地址
     * @return
     */
    public static String picUrl() {
        String url = "http://r234valei.hn-bkt.clouddn.com";
        String picUrl = url + "/" + KEY;
        return picUrl;
    }
}
